<template>
	<div class="app-container">
		<!-- 高级查询 -->
		<p>我要开单</p>
		<el-divider></el-divider>
		<el-steps :align-center="true" :active="active" finish-status="success">
			<el-step title="填写表单"></el-step>
			<el-step title="核对信息"></el-step>
			<el-step title="完成"></el-step>
		</el-steps>
		<el-divider></el-divider>
		<div v-if="active == 1">
			<div class="moneyBox">
				<div class="moneyChildBox">
					<div class="textAlLine eduTitle">预授信额度</div>
					<div class="titleNumber textAlLine"> {{ creditInfor.credit }}<span
							style="color: #818181;margin-left: 10px;">元</span> </div>
				</div>
				<div class="moneyChildBox">
					<div class="textAlLine eduTitle">可用额度</div>
					<div class="titleNumber textAlLine redColor">{{ creditInfor.creditLeft }}<span
							style="color: #818181;margin-left: 10px;">元</span> </div>
				</div>
				<div class="moneyChildBox">
					<div class="textAlLine eduTitle">已用额度</div>
					<div class="titleNumber textAlLine">46,568,54<span
							style="color: #818181;margin-left: 10px;">元</span> </div>
				</div>
				<div class="moneyChildBox">
					<div class="textAlLine eduTitle">冻结额度</div>
					<div class="titleNumber textAlLine">{{ creditInfor.frezeCredit }}<span
							style="color: #818181;margin-left: 10px;">元</span>
					</div>
				</div>
			</div>
			<el-divider></el-divider>
			<div class="contentBox">
				<el-form :rules="rules" ref="form" :model="form" label-width="80px">
         <!-- <el-form-item label="合同编号">
          		<el-input v-model="form.contractNo"></el-input>
          <el-col :span="1.5" style="float: right;">

              <el-button style="float: right;" type="primary" icon="el-icon-plus" size="mini" @click="openContractSelector">选择合同</el-button>
              <sales-order-item-selector :visible.sync="contractSelectorVisible" @selected="handleSelectedContract" />

           </el-col>
          	</el-form-item> -->
            <el-form-item label="合同编号">
                      		<el-input v-model="form.contractNo"></el-input>
                      <el-col :span="1.5" style="float: right;">
            
                          <el-button style="float: right;" type="primary" icon="el-icon-plus" size="mini" @click="openContractSelector">选择合同</el-button>
                          <sales-order-item-selector :visible.sync="contractSelectorVisible" @selected="handleSelectedContract" />
            
                       </el-col>
                      	</el-form-item>
					<el-form-item label="收单企业">
<!-- v-if="creditInfor.custType === `supplier`" -->
						<el-select  v-model="form.salerNo"
            style="width: 100%" filterable clearable
							placeholder="请选择收单企业" >
							<el-option v-for="option in options.supplierIdOptions" :key="option.id"
								:label="option.supplierName" :value="option.id" />
						</el-select>
          <!--  <el-select  v-if="creditInfor.custType === `customer`"   v-model="form.salerNo"
            style="width: 100%" filterable clearable
            	placeholder="请选择收单企业" >
            	<el-option v-for="option in options.customerIdOptions" :key="option.id"
            		:label="option.customerName" :value="option.id" />
            </el-select> -->
					</el-form-item>
					<!-- <el-form-item label="收单企业" prop="receiverNo">
						<el-select v-model="form.receiverNo" style="width: 100%" filterable clearable
							placeholder="请选择收单企业">
							<el-option v-for="option in options.supplierOptions" :key="option.id"
								:label="option.supplierName" :value="option.id" />
						</el-select>
					</el-form-item> -->
					<el-form-item label="惠单金额">
						<div style="display: flex;">
							<div>
								<el-input @input="smallToBig(form.amount)" style="width: 90px;" v-model="form.amount">
								</el-input>
							</div>
							<div style="font-weight: bold;margin-left: 10px;">RMB{{form.amount}}元</div>
							<div v-if="form.amount != ''" style="font-weight: bold;margin-left: 10px;">{{value}}</div>
						</div>

					</el-form-item>
					<el-form-item label="开单日">
						<el-col :span="10">
							<el-date-picker format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
								v-model="form.openDate" style="width: 90%;">
							</el-date-picker>
						</el-col>
						<el-col class="line" :span="4"> - 到期日 -</el-col>
						<el-col :span="10">
							<el-date-picker format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
								v-model="form.validatedTo" style="width: 100%;">
							</el-date-picker>
						</el-col>
					</el-form-item>
          <!-- <el-row :gutter="10" style="padding-top: 2px">
            <el-col :span="1.5" style="float: right;">
              <el-col :span="1.5" style="float: right;">
                <el-button style="float: right;" type="primary" icon="el-icon-plus" size="mini" @click="openBrandSelector">添加品牌</el-button>
                <brand-selector :visible.sync="brandSelectorVisible" @selected="handleSelectedBrand" />
              </el-col>
             </el-col>
          </el-row> -->

<!-- 	<el-form-item label="合同编号" prop="contractNo">
						<el-input v-model="form.contractNo"></el-input>
					</el-form-item> -->
					<el-form-item label="发票号码" prop="invoiceNo">
						<el-input v-model="form.invoiceNo "></el-input>
					</el-form-item>
         <!-- <el-form-item label="业务单号" prop="basicNo">
          	<el-input v-model="form.basicNo"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="产品" prop="productName">
          	<el-input v-model="form.productName"></el-input>
          </el-form-item> -->
					<el-form-item label="备注">
						<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容"
							v-model="form.remark">
						</el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="submitForm('form')">立即创建</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<div style="height: 500px;">
			<div v-if="active == 2" class="imgBg">
				<div class="xindanBox">
					<div class="topBox">
						<div class="title">
							<div
								style="text-align: center;font-size: 23px;border-bottom: 1px solid #555555;margin-top: 10px;height: 40px;">
								惠单</div>
							<div style="text-align: center;font-size: 14px;margin-top: 20px;">开单日期：{{form.openDate}}
							</div>
						</div>
						<div class="orderNo">
							<!-- <div style="font-weight: 700;font-size: 17px;margin-top: 30px;">惠单编号:</div>
							<div style="font-weight: 700;font-size: 17px;margin-top: 5px;">R9007932197981237132</div> -->
						</div>
					</div>
					<div>
						<table width="90%" height="300" border="1" style="border-collapse: collapse;margin: 0 auto;">
							<tr>
								<th scope="col" width="15%">开单方</th>
								<th scope="col" width="35%">{{form.receiverName}}</th>
								<th scope="col" width="15%">持单方</th>
								<th scope="col" width="35%">{{name}}</th>
							</tr>
							<tr>
								<td>兑付日期</td>
								<td>{{form.openDate}}</td>
								<td>期限</td>
								<td>{{dateBetween}}天</td>
							</tr>
							<tr>
								<td>金额</td>
								<td>
									<div style="display: flex;">
										<div>
											<p>人民币</p>
											<p>(大写)</p>
										</div>
										<h3 style="line-height: 50px;">{{value}}</h3>
									</div>

								</td>
								<td height="50" colspan="2">
									<table border="1" width="100%">
										<tr style="width: 100%;" height="50px">
											<th>亿</th>
											<th>千</th>
											<th>百</th>
											<th>十</th>
											<th>万</th>
											<th>千</th>
											<th>白</th>
											<th>十</th>
											<th>元</th>
										</tr>
										<tr height="50px">
											<td>{{a}}</td>
											<td>{{b}}</td>
											<td>{{c}}</td>
											<td>{{d}}</td>
											<td>{{e}}</td>
											<td>{{f}}</td>
											<td>{{g}}</td>
											<td>{{h}}</td>
											<td>{{i}}</td>
										</tr>
									</table>
								</td>
							<tr>
								<td>保贴方</td>
								<td>{{form.baoliCompany}}</td>
								<td>兑付方式</td>
								<td>电汇兑付</td>
							</tr>
							<tr>
								<td colspan="2">
									<div style="display: flex;">
										<div style="line-height: 100px;">开单方承诺：本惠单到期无条件兑付</div>
							<!-- 			<img src="../../../assets/img/pass.png" width="100px" height="100px"> -->
									</div>
								</td>
								<td colspan="2">
									<div style="display: flex;">
										<div style="line-height: 100px;">保贴方承诺：为本惠单无条件保贴</div>
						<!-- 				<img src="../../../assets/img/pass.png" width="100px" height="100px"> -->
									</div>
								</td>
							</tr>
							</tr>
						</table>
					</div>
				</div>
				<div style="margin: 0 auto;">
					<el-button @click="goBack">上一步</el-button>
					<el-button @click="confirm" type="primary">确认提交</el-button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import SupplierApi from '@/api/basic/SupplierApi';
	import CustomerApi from '@/api/basic/CustomerApi';
  import SalesOrderItemSelector from '@/views/order/salesOrder/SalesOrderItemSelector'
	import FinCreditBillApi from '@/api/baoli/FinCreditBillApi';
	export default {
		name: 'FinCreditBillImport',
    components: {
      SalesOrderItemSelector
    },
		data() {
			return {
				active: 1,
				value: '',
				name: '',
				options: {
					supplierIdOptions: [],
          customerIdOptions: [],
					supplierOptions: []
				},
        contractSelectorVisible: false,
				creditInfor: {
					credit: '',
          custType: '',
					creditLeft: '',
					frezeCredit: ''
				},
				form: {
					salerNo: '',
         	salerName: '',
          receiverName: '',
          baoliCompany: '',
					receiverNo: '',
					amount: '',
          productName: '',
          productNo: '',
          qty: '',
          unit: '',
					openDate: '',
					validatedTo: '',
					contractNo: '',
          basicNo: '',
					invoiceNo: '',
					remark: ''
				},
				a: '',
				b: '',
				c: '',
				d: '',
				e: '',
				f: '',
				g: '',
				h: '',
				i: '',
				dateBetween: '',
				rules: {
					salerNo: [{
							required: true,
							message: '请输入收单企业',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 25,
							message: '长度在 3 到 25 个字符',
							trigger: 'blur'
						}
					],
          contractNo: [{
          		required: true,
          		message: '请输入合同号',
          		trigger: 'blur'
          	},
          	{
          		min: 3,
          		max: 25,
          		message: '长度在 3 到 25 个字符',
          		trigger: 'blur'
          	}
          ]
				}
			}
		},
		created() {
			this.loadOptions()
		},
		methods: {
			goBack() {
				this.active = 1;
			},
      openContractSelector() {
        this.contractSelectorVisible = true
      },
      handleSelectedContract(contracts) {
        if (contracts && contracts.length > 0) {
          for (let i = 0; i < contracts.length; i++) {
            const contract = contracts[i]
             this.form.contractNo =contract.contractNo
             this.form.amount =contract.custRelSalesPrice
             this.form.productName =contract.skuName
             this.form.productNo =contract.custSkuId
                this.form.unit =contract.unit
                      this.form.qty =contract.qty
                        this.form.basicNo =contract.id
                         this.form.salerNo =contract.supplierNo
          /*  if (!isExisted) { */
            /*  this.brandList.push({
                brandId: brand.id,
                brandCode: brand.brandCode,
                brandName: brand.brandName,
                letter: brand.letter,
                logo: brand.logo,
                authExpDate: null, // 授权过期时间
                authNo: null, // 授权号
                authStartDate: null // 授权开始时间
              }) */
           /* } */
          }
        }
      },
			loadOptions() {
				let that = this;
				SupplierApi.list().then(res => {
					that.options.supplierIdOptions = res.data
					that.options.supplierOptions = res.data
				})
        CustomerApi.list().then(res => {
        	that.options.customerIdOptions = res.data

        })
				CustomerApi.getMyCustInfor().then(response => {
          that.creditInfor.custType=response.data.custType
					that.creditInfor.creditLeft = response.data.creditLeft
					that.creditInfor.credit = response.data.credit
					that.creditInfor.frezeCredit = response.data.frezeCredit
          that.form.receiverName = response.data.customerName
          that.form.baoliCompany= response.data.baoliCompanyName
				})
			},
			confirm() {
				FinCreditBillApi.submit(this.form).then(res =>{
					console.log(res)
				})
				this.active = 3;
				alert('提交成功')
				setTimeout(() => {
					this.active = 1;
				}, 1500);
				this.form = {
					salerNo: '',
					receiverNo: '',
					amount: '',
					openDate: '',
					validatedTo: '',
					contractNo: '',
					invoiceNo: '',
					remark: ''
				};
				this.dateBetween = '';
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						for(let i in this.options.supplierOptions){
							if(this.form.salerNo == this.options.supplierOptions[i].id){
								this.name = this.options.supplierOptions[i].supplierName
								// return
							}
						}
            for(let j in this.options.customerIdOptions){
            	if(this.form.salerNo == this.options.customerIdOptions[j].id){
            		this.name = this.options.customerIdOptions[j].customerName
            		// return
            	}
            }
						this.a = parseInt(this.form.amount / 100000000)
						this.b = parseInt(this.form.amount % 100000000 / 10000000)
						this.c = parseInt(this.form.amount % 100000000 % 10000000 / 1000000)
						this.d = parseInt(this.form.amount % 100000000 % 10000000 % 1000000 / 100000)
						this.e = parseInt(this.form.amount % 100000000 % 10000000 % 1000000 % 100000 / 10000)
						this.f = parseInt(this.form.amount % 100000000 % 10000000 % 1000000 % 100000 % 10000 /
							1000)
						this.g = parseInt(this.form.amount % 100000000 % 10000000 % 1000000 % 100000 % 10000 %
							1000 / 100)
						this.h = parseInt(this.form.amount % 100000000 % 10000000 % 1000000 % 100000 % 10000 %
							1000 % 100 / 10)
						this.i = parseInt(this.form.amount % 100000000 % 10000000 % 1000000 % 100000 % 10000 %
							1000 % 100 % 10 / 1)
						this.active = 2
						console.log(this.form.openDate)
						this.getDaysBetween(this.form.openDate, this.form.validatedTo)
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			// *
			//  * 计算两个日期之间的天数
			//  * @param dateString1  开始日期 yyyy-MM-dd
			//  * @param dateString2  结束日期 yyyy-MM-dd
			//  * @returns {number} 如果日期相同 返回一天 开始日期大于结束日期，返回0
			getDaysBetween(dateString1, dateString2) {
				var startDate = Date.parse(dateString1);
				var endDate = Date.parse(dateString2);
				if (startDate > endDate) {
					return 0;
				}
				if (startDate == endDate) {
					return 1;
				}
				var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
				this.dateBetween = days
			},
			smallToBig(money) {
				//  将数字金额转换为大写金额
				var cnNums = new Array(
					"零",
					"壹",
					"贰",
					"叁",
					"肆",
					"伍",
					"陆",
					"柒",
					"捌",
					"玖"
				); //汉字的数字
				var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
				var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
				var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
				var cnInteger = "整"; //整数金额时后面跟的字符
				var cnIntLast = "元"; //整数完以后的单位
				//最大处理的数字
				var maxNum = 999999999999999.9999;
				var integerNum; //金额整数部分
				var decimalNum; //金额小数部分
				//输出的中文金额字符串
				var chineseStr = "";
				var parts; //分离金额后用的数组，预定义
				if (money == "") {
					return "";
				}

				money = parseFloat(money);
				if (money >= maxNum) {
					//超出最大处理数字
					return "超出最大处理数字";
				}
				if (money == 0) {
					chineseStr = cnNums[0] + cnIntLast + cnInteger;
					return chineseStr;
				}

				//四舍五入保留两位小数,转换为字符串
				money = Math.round(money * 100).toString();
				integerNum = money.substr(0, money.length - 2);
				decimalNum = money.substr(money.length - 2);

				//获取整型部分转换
				if (parseInt(integerNum, 10) > 0) {
					var zeroCount = 0;
					var IntLen = integerNum.length;
					for (var i = 0; i < IntLen; i++) {
						var n = integerNum.substr(i, 1);
						var p = IntLen - i - 1;
						var q = p / 4;
						var m = p % 4;
						if (n == "0") {
							zeroCount++;
						} else {
							if (zeroCount > 0) {
								chineseStr += cnNums[0];
							}
							//归零
							zeroCount = 0;
							chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
						}
						if (m == 0 && zeroCount < 4) {
							chineseStr += cnIntUnits[q];
						}
					}
					chineseStr += cnIntLast;
				}
				//小数部分
				if (decimalNum != "") {
					var decLen = decimalNum.length;
					for (var i = 0; i < decLen; i++) {
						var n = decimalNum.substr(i, 1);
						if (n != "0") {
							chineseStr += cnNums[Number(n)] + cnDecUnits[i];
						}
					}
				}
				if (chineseStr == "") {
					chineseStr += cnNums[0] + cnIntLast + cnInteger;
				} else if (decimalNum == "" || /^0*$/.test(decimalNum)) {
					chineseStr += cnInteger;
				}
				this.value = chineseStr;
				console.log(this.value)
			}
		}
	}
</script>
<style scoped>
	.imgBg {
		width: 80%;
		margin: 0 auto;
		height: 430px;
		background-image: url("../../../assets/img/wenli.png");
		/*background: url("img/2.jpg") 10% 20% no-repeat;!*图片从左往右移动的百分比大小，从上往下百分比大小，重复方式
		                                                            换成数值同样如此，在这里没有调整大小的方法*!*/
		/*这个是按从左往右，从上往下的百分比位置进行调整*/
		background-size: 100% 100%;
		/*按比例缩放*/
		/*background-size: 100px 100px;!*这个是按数值缩放*!*/
		background-repeat: no-repeat;
		/*还有repeat-x,y等*/
	}

	.xindanBox {
		width: 95%;
		height: 450px;
		margin: 0 auto;
	}

	.topBox {
		display: flex;

	}

	.title {
		height: 100px;
		width: 40%;
		margin: 0 auto;
		margin-left: 30%;
	}

	.orderNo {
		height: 100px;
		width: 30%;
		margin-left: 50px;
	}

	.moneyBox {
		display: flex;
		height: 50px;
		width: 100%;
	}

	.moneyChildBox {
		width: 25%;
		height: 50px;
	}

	.textAlLine {
		text-align: center;
	}

	.eduTitle {
		/* margin-top: 30px; */
		color: #818181;
		font-size: 15px;
	}

	.redColor {
		color: #fd0000;
	}

	.titleNumber {
		margin-top: 10px;
		font-weight: bold;
	}

	.contentBox {
		width: 50%;
		margin: 0 auto;
		/* height: 300px; */
	}
</style>
